za<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>审核管理 - 沥青运输管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        .status-approved {
            background-color: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .review-card {
            transition: transform 0.2s;
            cursor: pointer;
        }
        .review-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,.15);
        }
        .filter-section {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .disabled-link {
            cursor: not-allowed;
            opacity: 0.6;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-2 d-none d-md-block bg-light sidebar">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="/">
                                <span data-feather="home"></span>
                                仪表板
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="/review/">
                                <span data-feather="check-circle"></span>
                                审核管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled-link" href="#" onclick="alert('该功能暂未开放'); return false;">
                                <span data-feather="users"></span>
                                用户管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled-link" href="#" onclick="alert('该功能暂未开放'); return false;">
                                <span data-feather="truck"></span>
                                车辆管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link disabled-link" href="#" onclick="alert('该功能暂未开放'); return false;">
                                <span data-feather="package"></span>
                                订单管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/profile/">
                                <span data-feather="user"></span>
                                个人中心
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">审核管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <button type="button" class="btn btn-sm btn-outline-secondary" id="refreshBtn">
                                刷新
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 筛选器 -->
                <div class="filter-section">
                    <div class="row">
                        <div class="col-md-3 mb-2">
                            <label class="form-label">审核类型</label>
                            <select class="form-select" id="typeFilter">
                                <option value="">全部类型</option>
                                <option value="user">用户资质审核</option>
                                <option value="vehicle">车辆资质审核</option>
                            </select>
                        </div>
                        <div class="col-md-3 mb-2">
                            <label class="form-label">审核状态</label>
                            <select class="form-select" id="statusFilter">
                                <option value="">全部状态</option>
                                <option value="pending">待审核</option>
                                <option value="approved">已通过</option>
                                <option value="rejected">已拒绝</option>
                            </select>
                        </div>
                        <div class="col-md-3 mb-2">
                            <label class="form-label">时间范围</label>
                            <select class="form-select" id="timeFilter">
                                <option value="">全部时间</option>
                                <option value="today">今天</option>
                                <option value="week">本周</option>
                                <option value="month">本月</option>
                            </select>
                        </div>
                        <div class="col-md-3 mb-2 d-flex align-items-end">
                            <button type="button" class="btn btn-primary w-100" id="applyFilter">
                                应用筛选
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 统计信息 -->
                <div class="row mb-4" id="statsSection">
                    <div class="col-md-4">
                        <div class="card text-white bg-warning" style="cursor: pointer;" onclick="window.location.href='/review/list/?status=pending'">
                            <div class="card-body">
                                <h5 class="card-title">待审核</h5>
                                <h2 id="pendingCount">0</h2>
                                <p class="card-text" style="font-size: 0.8rem; opacity: 0.9;">需要尽快处理的申请</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card text-white bg-success" style="cursor: pointer;" onclick="window.location.href='/review/list/?status=approved'">
                            <div class="card-body">
                                <h5 class="card-title">已通过</h5>
                                <h2 id="approvedCount">0</h2>
                                <p class="card-text" style="font-size: 0.8rem; opacity: 0.9;">已审核通过的申请</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card text-white bg-danger" style="cursor: pointer;" onclick="window.location.href='/review/list/?status=rejected'">
                            <div class="card-body">
                                <h5 class="card-title">已拒绝</h5>
                                <h2 id="rejectedCount">0</h2>
                                <p class="card-text" style="font-size: 0.8rem; opacity: 0.9;">不符合要求的申请</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 审核列表 -->
                <div class="row" id="reviewList">
                    <!-- 审核项将通过JavaScript动态加载 -->
                    <div class="col-12 text-center py-5">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                </div>

                <!-- 分页 -->
                <nav aria-label="分页导航" class="mt-4">
                    <ul class="pagination justify-content-center" id="pagination">
                        <!-- 分页按钮将通过JavaScript动态生成 -->
                    </ul>
                </nav>
            </main>
        </div>
    </div>

    <!-- 审核详情模态框 -->
    <div class="modal fade" id="reviewModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="reviewModalLabel">审核详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body" id="reviewModalBody">
                    <!-- 审核详情内容 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <a href="#" id="detailLink" class="btn btn-primary">详细信息</a>
                </div>
            </div>
        </div>
    </div>

    <!-- 拒绝原因模态框 -->
    <div class="modal fade" id="rejectModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">拒绝审核</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <form id="rejectForm">
                        <input type="hidden" id="rejectReviewId">
                        <div class="mb-3">
                            <label for="rejectReason" class="form-label">拒绝原因</label>
                            <textarea class="form-control" id="rejectReason" rows="3" required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="submitReject">确认拒绝</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let currentPage = 1;
        let currentFilters = {};
        
        // 页面加载完成后获取审核列表
        document.addEventListener('DOMContentLoaded', function() {
            // 从URL参数中获取筛选条件并设置到筛选器中
            const urlParams = new URLSearchParams(window.location.search);
            const statusParam = urlParams.get('status');
            if (statusParam) {
                document.getElementById('statusFilter').value = statusParam;
            }
            
            const typeParam = urlParams.get('type');
            if (typeParam) {
                document.getElementById('typeFilter').value = typeParam;
            }
            
            fetchReviews();
            fetchStats();
            
            // 绑定事件监听器
            document.getElementById('refreshBtn').addEventListener('click', function() {
                fetchReviews();
                fetchStats();
            });
            
            // 监听筛选条件变化
            document.getElementById('typeFilter').addEventListener('change', function() {
                currentPage = 1;
                fetchReviews();
                fetchStats();
            });
            
            document.getElementById('statusFilter').addEventListener('change', function() {
                currentPage = 1;
                fetchReviews();
                fetchStats();
            });
            
            document.getElementById('timeFilter').addEventListener('change', function() {
                currentPage = 1;
                fetchReviews();
                fetchStats();
            });
            
            // 移除应用筛选按钮的事件监听器
            // document.getElementById('applyFilter').addEventListener('click', function() {
            //     currentPage = 1;
            //     fetchReviews();
            //     fetchStats();
            // });
        });
        
        // 获取统计信息
        function fetchStats() {
            // 获取待审核数量
            fetch('/api/admin/review/pending/')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('pendingCount').textContent = data.count || 0;
                })
                .catch(error => {
                    console.error('获取待审核数量失败:', error);
                    document.getElementById('pendingCount').textContent = '错误';
                });

            // 获取总的统计信息
            fetch('/api/admin/review/history/')
                .then(response => response.json())
                .then(data => {
                    const stats = {
                        approved: 0,
                        rejected: 0
                    };
                    
                    if (data.results) {
                        data.results.forEach(review => {
                            if (review.status === 'approved') stats.approved++;
                            else if (review.status === 'rejected') stats.rejected++;
                        });
                        
                        document.getElementById('approvedCount').textContent = stats.approved;
                        document.getElementById('rejectedCount').textContent = stats.rejected;
                    }
                })
                .catch(error => {
                    console.error('获取统计信息失败:', error);
                });
        }
        
        // 获取审核列表
        function fetchReviews() {
            // 显示加载状态
            document.getElementById('reviewList').innerHTML = `
                <div class="col-12 text-center py-5">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>
            `;
            
            // 构建查询参数
            const params = new URLSearchParams();
            params.append('page', currentPage);
            params.append('page_size', 12); // 每页显示12条记录
            
            const typeFilter = document.getElementById('typeFilter').value;
            if (typeFilter) {
                params.append('type', typeFilter);
                currentFilters.type = typeFilter;
            } else {
                delete currentFilters.type;
            }
            
            const statusFilter = document.getElementById('statusFilter').value;
            if (statusFilter) {
                params.append('status', statusFilter);
                currentFilters.status = statusFilter;
            } else {
                delete currentFilters.status;
            }
            
            // 发送请求
            fetch(`/api/admin/review/history/?${params.toString()}`)
                .then(response => response.json())
                .then(data => {
                    renderReviews(data);
                })
                .catch(error => {
                    console.error('获取审核列表失败:', error);
                    document.getElementById('reviewList').innerHTML = `
                        <div class="col-12">
                            <div class="alert alert-danger" role="alert">
                                加载审核列表失败，请稍后重试。
                            </div>
                        </div>
                    `;
                });
        }
        
        // 渲染审核列表
        function renderReviews(data) {
            const reviewList = document.getElementById('reviewList');
            
            if (!data.results || data.results.length === 0) {
                reviewList.innerHTML = `
                    <div class="col-12">
                        <div class="alert alert-info" role="alert">
                            暂无审核记录。
                        </div>
                    </div>
                `;
                renderPagination(data);
                return;
            }
            
            let html = '';
            data.results.forEach(review => {
                html += `
                    <div class="col-md-6 col-lg-4 mb-4">
                        <div class="card review-card h-100" onclick="showReviewDetail(${review.id})">
                            <div class="card-body">
                                <h5 class="card-title">${getReviewTypeDisplay(review.type)}</h5>
                                <p class="card-text">
                                    <strong>状态:</strong> 
                                    <span class="badge ${getStatusClass(review.status)}">
                                        ${getStatusDisplay(review.status)}
                                    </span>
                                </p>
                                <p class="card-text">
                                    <strong>提交时间:</strong> ${formatDate(review.submitted_at)}
                                </p>
                                ${review.reviewed_at ? `
                                <p class="card-text">
                                    <strong>审核时间:</strong> ${formatDate(review.reviewed_at)}
                                </p>
                                ` : ''}
                                ${review.reviewer ? `
                                <p class="card-text">
                                    <strong>审核员:</strong> ${review.reviewer}
                                </p>
                                ` : ''}
                            </div>
                            <div class="card-footer">
                                <button class="btn btn-primary btn-sm" onclick="showReviewDetail(${review.id}); event.stopPropagation();">
                                    查看详情
                                </button>
                                ${review.status === 'pending' ? `
                                <button class="btn btn-success btn-sm" onclick="approveReview(${review.id}, 'approved'); event.stopPropagation();">
                                    通过
                                </button>
                                <button class="btn btn-danger btn-sm" onclick="showRejectModal(${review.id}); event.stopPropagation();">
                                    拒绝
                                </button>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                `;
            });
            
            reviewList.innerHTML = html;
            renderPagination(data);
        }
        
        // 渲染分页控件
        function renderPagination(data) {
            const pagination = document.getElementById('pagination');
            
            // 计算总页数 (假设每页12条记录)
            const totalPages = Math.ceil(data.count / 12);
            
            let html = '';
            
            // 上一页
            if (currentPage > 1) {
                html += `
                    <li class="page-item">
                        <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a>
                    </li>
                `;
            }
            
            // 页码 (只显示当前页前后各3页)
            const startPage = Math.max(1, currentPage - 3);
            const endPage = Math.min(totalPages, currentPage + 3);
            
            for (let i = startPage; i <= endPage; i++) {
                if (i === currentPage) {
                    html += `
                        <li class="page-item active">
                            <span class="page-link">${i}</span>
                        </li>
                    `;
                } else {
                    html += `
                        <li class="page-item">
                            <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                        </li>
                    `;
                }
            }
            
            // 下一页
            if (currentPage < totalPages) {
                html += `
                    <li class="page-item">
                        <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a>
                    </li>
                `;
            }
            
            pagination.innerHTML = html;
        }
        
        // 切换页面
        function changePage(page) {
            currentPage = page;
            fetchReviews();
        }
        
        // 显示审核详情
        function showReviewDetail(reviewId) {
            fetch(`/api/admin/review/${reviewId}/`)
                .then(response => response.json())
                .then(review => {
                    const modalBody = document.getElementById('reviewModalBody');
                    modalBody.innerHTML = `
                        <div class="row">
                            <div class="col-md-6">
                                <h6>基本信息</h6>
                                <table class="table table-borderless">
                                    <tr>
                                        <td><strong>审核类型:</strong></td>
                                        <td>${getReviewTypeDisplay(review.type)}</td>
                                    </tr>
                                    <tr>
                                        <td><strong>状态:</strong></td>
                                        <td>
                                            <span class="badge ${getStatusClass(review.status)}">
                                                ${getStatusDisplay(review.status)}
                                            </span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td><strong>提交时间:</strong></td>
                                        <td>${formatDate(review.submitted_at)}</td>
                                    </tr>
                                    ${review.reviewed_at ? `
                                    <tr>
                                        <td><strong>审核时间:</strong></td>
                                        <td>${formatDate(review.reviewed_at)}</td>
                                    </tr>
                                    ` : ''}
                                    ${review.reviewer ? `
                                    <tr>
                                        <td><strong>审核员:</strong></td>
                                        <td>${review.reviewer}</td>
                                    </tr>
                                    ` : ''}
                                </table>
                            </div>
                            <div class="col-md-6">
                                <h6>关联信息</h6>
                                ${review.type === 'user' && review.user ? `
                                <table class="table table-borderless">
                                    <tr>
                                        <td><strong>用户:</strong></td>
                                        <td>${review.user.phone}</td>
                                    </tr>
                                    <tr>
                                        <td><strong>公司:</strong></td>
                                        <td>${review.user.company || '无'}</td>
                                    </tr>
                                    <tr>
                                        <td><strong>信用评分:</strong></td>
                                        <td>${review.user.credit_score}</td>
                                    </tr>
                                </table>
                                ` : ''}
                                ${review.type === 'vehicle' && review.vehicle ? `
                                <table class="table table-borderless">
                                    <tr>
                                        <td><strong>车牌号:</strong></td>
                                        <td>${review.vehicle.license_plate}</td>
                                    </tr>
                                    <tr>
                                        <td><strong>车辆类型:</strong></td>
                                        <td>${review.vehicle.vehicle_type}</td>
                                    </tr>
                                    <tr>
                                        <td><strong>载重:</strong></td>
                                        <td>${review.vehicle.capacity} 吨</td>
                                    </tr>
                                    <tr>
                                        <td><strong>车主:</strong></td>
                                        <td>${review.vehicle.user.phone}</td>
                                    </tr>
                                </table>
                                ` : ''}
                            </div>
                            <div class="col-12">
                                <h6>审核说明</h6>
                                <p>${review.reason || '无'}</p>
                            </div>
                        </div>
                        ${review.status === 'pending' ? `
                        <div class="mt-3">
                            <button class="btn btn-success" onclick="approveReview(${review.id}, 'approved')">
                                通过审核
                            </button>
                            <button class="btn btn-danger" onclick="showRejectModal(${review.id})">
                                拒绝审核
                            </button>
                        </div>
                        ` : ''}
                    `;
                    
                    // 设置详细信息链接
                    document.getElementById('detailLink').href = '/review/detail/' + reviewId + '/';
                    
                    const modal = new bootstrap.Modal(document.getElementById('reviewModal'));
                    modal.show();
                })
                .catch(error => {
                    console.error('获取审核详情失败:', error);
                    alert('获取审核详情失败');
                });
        }
        
        // 通过审核
        function approveReview(reviewId, status) {
            if (!confirm('确定要通过此审核吗？')) {
                return;
            }
            
            fetch(`/api/admin/review/${reviewId}/approve/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    status: status
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert('审核失败: ' + data.error);
                } else {
                    alert('审核已通过');
                    // 关闭可能打开的模态框
                    const reviewModal = document.getElementById('reviewModal');
                    if (reviewModal.classList.contains('show')) {
                        bootstrap.Modal.getInstance(reviewModal).hide();
                    }
                    fetchReviews(); // 刷新列表
                    fetchStats(); // 刷新统计
                }
            })
            .catch(error => {
                console.error('审核失败:', error);
                alert('审核失败');
            });
        }
        
        // 显示拒绝模态框
        function showRejectModal(reviewId) {
            document.getElementById('rejectReviewId').value = reviewId;
            document.getElementById('rejectReason').value = '';
            
            // 关闭可能打开的详情模态框
            const reviewModal = document.getElementById('reviewModal');
            if (reviewModal.classList.contains('show')) {
                bootstrap.Modal.getInstance(reviewModal).hide();
            }
            
            // 打开拒绝模态框
            const modal = new bootstrap.Modal(document.getElementById('rejectModal'));
            modal.show();
        }
        
        // 拒绝审核
        function rejectReview(reviewId, reason) {
            fetch(`/api/admin/review/${reviewId}/approve/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    status: 'rejected',
                    reason: reason
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert('审核失败: ' + data.error);
                } else {
                    alert('审核已拒绝');
                    // 关闭拒绝模态框
                    const rejectModal = document.getElementById('rejectModal');
                    bootstrap.Modal.getInstance(rejectModal).hide();
                    fetchReviews(); // 刷新列表
                    fetchStats(); // 刷新统计
                }
            })
            .catch(error => {
                console.error('审核失败:', error);
                alert('审核失败');
            });
        }
        
        // 工具函数：获取审核类型显示文本
        function getReviewTypeDisplay(type) {
            switch (type) {
                case 'user': return '用户资质审核';
                case 'vehicle': return '车辆资质审核';
                default: return type;
            }
        }
        
        // 工具函数：获取状态显示文本
        function getStatusDisplay(status) {
            switch (status) {
                case 'pending': return '待审核';
                case 'approved': return '已通过';
                case 'rejected': return '已拒绝';
                default: return status;
            }
        }
        
        // 工具函数：获取状态CSS类
        function getStatusClass(status) {
            switch (status) {
                case 'pending': return 'status-pending';
                case 'approved': return 'status-approved';
                case 'rejected': return 'status-rejected';
                default: return '';
            }
        }
        
        // 工具函数：格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }
        
        // 工具函数：获取Cookie
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    </script>
</body>
</html>